package com.tul.exercise.base.java8.stream.collector;

import com.tul.exercise.base.java8.common.Constant;
import com.tul.exercise.base.java8.stream.base.Artist;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * java 8中操作HashMap的一些使用示例
 * @author tuliang
 */
public class MapTest {

    @Test
    @DisplayName("Java 8 中map的遍历新方式")
    public void test01() {
        List<Artist> list = Artist.createArtists(20);
        Map<String, List<Artist>> map = list.stream().collect(Collectors.groupingBy(Artist::getFrom));

        map.forEach((key, value) ->{
            System.out.println("key=" + key);
            System.out.println("value=" + value);
        });
    }

    @Test
    @DisplayName("map的computeIfAbsent()方法的使用")
    public void test02() {
        Map<String, Artist> map = new HashMap<>(100);

        Function<String, Artist> createFromName= (name) -> {return new Artist(name, "China");};
        for (int i = 0; i < Constant.ARTIST_NAMES.size(); i++) {
            String name = Constant.ARTIST_NAMES.get(i);
            Artist artist = map.computeIfAbsent(name, createFromName);
            System.out.println(artist);
        }
    }
}
